package com.uaa.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author iszengziqiang@163.com
 * @date 2021-10-22 16:46
 * @Version: 1.0
 * @desc
 */
@Configuration
@EnableWebSecurity//开启springsecurity过滤链filter
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    //认证管理器
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    //密码编码器
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    //安全拦截机制（最重要）
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()// CRSF禁用，因为不使用session
                .authorizeRequests()// 过滤请求
                .antMatchers("/r2","/oauth/token").anonymous()//不需要认证
                .anyRequest().authenticated()//其他需要认证
                .and()
                .formLogin();

//        http.authorizeRequests()
//                .antMatchers("/r2").anonymous()
//                .anyRequest().authenticated()
//                .and()
//                .formLogin()
//        ;


    }

    public static void main(String[] args) {
        String secret = new BCryptPasswordEncoder().encode("secret");
        System.out.println(secret);
    }
}
